package org.alex.nettychat.netty.custom;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.alex.nettychat.netty.custom.console.ConsoleCommandManager;
import org.alex.nettychat.netty.custom.console.Login;
import org.alex.nettychat.netty.custom.handler.*;
import org.alex.nettychat.netty.custom.utils.SessionUtil;

import java.time.LocalDateTime;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * Netty 客户端
 *
 * @author : alex
 */
public class NettyClient {

    public static int MAX_RETRY = 5;

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        // 处理粘包 半包问题
                        channel.pipeline().addLast(new Spliter());
                        channel.pipeline().addLast(new PacketDecoder());
                        channel.pipeline().addLast(new LoginResponseHandler());
                        channel.pipeline().addLast(new CreateGroupResponseHandler());
                        channel.pipeline().addLast(new JoinGroupResponseHandler());
                        channel.pipeline().addLast(new QuitGroupResponseHandler());
                        channel.pipeline().addLast(new GetGroupInfoResponseHandler());
                        channel.pipeline().addLast(new SendToGroupResponseHandler());
                        channel.pipeline().addLast(new MessageResponseHandler());
                        channel.pipeline().addLast(new PacketEncoder());
                    }
                });

        connect(bootstrap, "127.0.0.1", 8000, MAX_RETRY);
    }

    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        bootstrap.connect(host, port).addListener((future) -> {
            if (future.isSuccess()) {
                System.out.println("连接成功");
                // 启动控制台线程
                Channel channel = ((ChannelFuture) future).channel();
                startConsoleThread(channel);
            } else if (retry == 0) {
                System.out.println("连接失败,重试次数已用完，放弃本次连接");

            } else {
                // 第几次重连
                int order = MAX_RETRY - retry + 1;

                // 本次重连间隔
                int delay = 1 << order;

                System.out.println(LocalDateTime.now() + ":连接失败，第" + order + "次重连......");
                // 重连
                int retry1 = retry - 1;
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry1), delay, TimeUnit.SECONDS);
            }
        });
    }

    /**
     * 启动控制台线程
     */
    private static void startConsoleThread(Channel channel) {
        Scanner scanner = new Scanner(System.in);
        ConsoleCommandManager consoleCommandManager = new ConsoleCommandManager();
        new Thread(() -> {
            while (!Thread.interrupted()) {
                if (!SessionUtil.hasLogin(channel)) {
                    new Login().exec(scanner, channel);

                    try {
                        // 防止channel未响应就继续轮询
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    consoleCommandManager.exec(scanner, channel);
                }
            }
        }).start();
    }
}
